package com.concurrent.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Date 2020/8/5 11:52
 * @Author admin
 * @Description
 */
public class CompletionServiceDemo {

    //创建线程池
    ExecutorService executor = Executors.newFixedThreadPool(3);
    //创建CompletionService
    CompletionService<Integer> cs = new ExecutorCompletionService<>(executor);

    //用于保存future对象
    List<Future<Integer>> futures = new ArrayList<>(3);


    public static void main(String[] args) {

        CompletionServiceDemo serviceDemo = new CompletionServiceDemo();
        //异步向电商s1询价
        serviceDemo.futures.add(serviceDemo.cs.submit(() -> getPriceByS1()));
        //异步向电商s2询价
        serviceDemo.cs.submit(() -> getPriceByS2());
        //异步向电商s3询价
        serviceDemo.cs.submit(() -> getPriceByS3());

        //将询价结果保存到数据库
        for (int i = 0; i < 3; i++) {
            Integer integer = null;
            try {
                integer = serviceDemo.cs.take().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            Integer finalInteger = integer;
            serviceDemo.executor.submit(()->save(finalInteger));
        }

        Integer r= 0;
        try {
            //只要有一个成功返回，则break;
            for (int i = 0; i < 3; i++) {
                try {
                    r= serviceDemo.cs.take().get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                //简单通过判空检查是否成功返回
                if(r!=null){
                    break;
                }
            }
        }finally {
            //取消所有任务
            for (Future<Integer> f : serviceDemo.futures) {
                f.cancel(true);
            }
        }

    }

    private static void save(Integer integer) {

    }

    private static Integer getPriceByS1() {
        return null;
    }
    private static Integer getPriceByS2() {
        return null;
    }
    private static Integer getPriceByS3() {
        return null;
    }


}
